You are currently looking at version 1.0 of this notebook. To download notebooks and datafiles, as well as get help on Jupyter notebooks in the Coursera platform, visit the Jupyter Notebook FAQ course resource.
This assignment is based on a data challenge from the Michigan Data Science Team (MDST).
The Michigan Data Science Team (MDST) and the Michigan Student Symposium for Interdisciplinary Statistical Sciences (MSSISS) have partnered with the City of Detroit to help solve one of the most pressing problems facing Detroit - blight. Blight violations are issued by the city to individuals who allow their properties to remain in a deteriorated condition. Every year, the city of Detroit issues millions of dollars in fines to residents and every year, many of these fines remain unpaid. Enforcing unpaid blight fines is a costly and tedious process, so the city wants to know: how can we increase blight ticket compliance?
The first step in answering this question is understanding when and why a resident might fail to comply with a blight ticket. This is where predictive modeling comes in. For this assignment, your task is to predict whether a given blight ticket will be paid on time.
All data for this assignment has been provided to us through the Detroit Open Data Portal. Only the data already included in your Coursera directory can be used for training the model for this assignment. Nonetheless, we encourage you to look into data from other Detroit datasets to help inform feature creation and model selection. We recommend taking a look at the following related datasets:
We provide you with two data files for use in training and validating your models: train.csv and test.csv. Each row in these two files corresponds to a single blight ticket, and includes information about when, why, and to whom each ticket was issued. The target variable is compliance, which is True if the ticket was paid early, on time, or within one month of the hearing data, False if the ticket was paid after the hearing date or not at all, and Null if the violator was found not responsible. Compliance, as well as a handful of other variables that will not be available at test-time, are only included in train.csv.
Note: All tickets where the violators were found not responsible are not considered during evaluation. They are included in the training set as an additional source of data for visualization, and to enable unsupervised and semi-supervised approaches. However, they are not included in the test set.
File descriptions (Use only this data for training your model!)
train.csv - the training set (all tickets issued 2004-2011)
test.csv - the test set (all tickets issued 2012-2016)
addresses.csv & latlons.csv - mapping from ticket id to addresses, and from addresses to lat/lon coordinates.
Note: misspelled addresses may be incorrectly geolocated.
Data fields
train.csv & test.csv
ticket_id - unique identifier for tickets
agency_name - Agency that issued the ticket
inspector_name - Name of inspector that issued the ticket
violator_name - Name of the person/organization that the ticket was issued to
violation_street_number, violation_street_name, violation_zip_code - Address where the violation occurred
mailing_address_str_number, mailing_address_str_name, city, state, zip_code, non_us_str_code, country - Mailing address of the violator
ticket_issued_date - Date and time the ticket was issued
hearing_date - Date and time the violator's hearing was scheduled
violation_code, violation_description - Type of violation
disposition - Judgment and judgement type
fine_amount - Violation fine amount, excluding fees
admin_fee - $20 fee assigned to responsible judgments
state_fee - $10 fee assigned to responsible judgments late_fee - 10% fee assigned to responsible judgments discount_amount - discount applied, if any clean_up_cost - DPW clean-up or graffiti removal cost judgment_amount - Sum of all fines and fees grafitti_status - Flag for graffiti violations
train.csv only
payment_amount - Amount paid, if any
payment_date - Date payment was made, if it was received
payment_status - Current payment status as of Feb 1 2017
balance_due - Fines and fees still owed
collection_status - Flag for payments in collections
compliance [target variable for prediction]
Null = Not responsible
0 = Responsible, non-compliant
1 = Responsible, compliant
compliance_detail - More information on why each ticket was marked compliant or non-compliant
Your predictions will be given as the probability that the corresponding blight ticket will be paid on time.
The evaluation metric for this assignment is the Area Under the ROC Curve (AUC).
Your grade will be based on the AUC score computed for your classifier. A model which with an AUROC of 0.7 passes this assignment, over 0.75 will recieve full points.
For this assignment, create a function that trains a model to predict blight ticket compliance in Detroit using train.csv
. Using this model, return a series of length 61001 with the data being the probability that each corresponding ticket from test.csv
will be paid, and the index being the ticket_id.
Example:
ticket_id
284932 0.531842
285362 0.401958
285361 0.105928
285338 0.018572
...
376499 0.208567
376500 0.818759
369851 0.018528
Name: compliance, dtype: float32
In [1]:
import pandas as pd
import numpy as np
def blight_model():
# Your code here
return # Your answer here
In [2]:
df_train = pd.read_csv('train.csv', encoding = "ISO-8859-1")
df_test = pd.read_csv('test.csv', encoding = "ISO-8859-1")
df_train.columns
Out[2]:
In [3]:
list_to_remove = ['balance_due',
'collection_status',
'compliance_detail',
'payment_amount',
'payment_date',
'payment_status']
list_to_remove_all = ['violator_name', 'zip_code', 'country', 'city',
'inspector_name', 'violation_street_number', 'violation_street_name',
'violation_zip_code', 'violation_description',
'mailing_address_str_number', 'mailing_address_str_name',
'non_us_str_code',
'ticket_issued_date', 'hearing_date']
In [4]:
df_train.drop(list_to_remove, axis=1, inplace=True)
df_train.drop(list_to_remove_all, axis=1, inplace=True)
df_test.drop(list_to_remove_all, axis=1, inplace=True)
df_train.drop('grafitti_status', axis=1, inplace=True)
df_test.drop('grafitti_status', axis=1, inplace=True)
In [5]:
df_train.head()
Out[5]:
In [6]:
df_train.violation_code.unique().size
Out[6]:
In [7]:
df_train.disposition.unique().size
Out[7]:
In [8]:
df_latlons = pd.read_csv('latlons.csv')
In [9]:
df_latlons.head()
Out[9]:
In [10]:
df_address = pd.read_csv('addresses.csv')
df_address.head()
Out[10]:
In [11]:
df_id_latlons = df_address.set_index('address').join(df_latlons.set_index('address'))
In [12]:
df_id_latlons.head()
Out[12]:
In [13]:
df_train = df_train.set_index('ticket_id').join(df_id_latlons.set_index('ticket_id'))
df_test = df_test.set_index('ticket_id').join(df_id_latlons.set_index('ticket_id'))
In [14]:
df_train.head()
Out[14]:
In [15]:
df_train.agency_name.value_counts()
Out[15]:
In [16]:
# df_train.country.value_counts()
# so we remove zip code and country as well
In [17]:
vio_code_freq10 = df_train.violation_code.value_counts().index[0:10]
vio_code_freq10
Out[17]:
In [18]:
df_train['violation_code_freq10'] = [list(vio_code_freq10).index(c) if c in vio_code_freq10 else -1 for c in df_train.violation_code ]
In [19]:
df_train.head()
Out[19]:
In [20]:
df_train.violation_code_freq10.value_counts()
Out[20]:
In [21]:
# drop violation code
df_train.drop('violation_code', axis=1, inplace=True)
df_test['violation_code_freq10'] = [list(vio_code_freq10).index(c) if c in vio_code_freq10 else -1 for c in df_test.violation_code ]
df_test.drop('violation_code', axis=1, inplace=True)
In [22]:
#df_train.grafitti_status.fillna('None', inplace=True)
#df_test.grafitti_status.fillna('None', inplace=True)
In [23]:
df_train = df_train[df_train.compliance.isnull() == False]
In [24]:
df_train.isnull().sum()
Out[24]:
In [25]:
df_test.isnull().sum()
Out[25]:
In [26]:
df_train.lat.fillna(method='pad', inplace=True)
df_train.lon.fillna(method='pad', inplace=True)
df_train.state.fillna(method='pad', inplace=True)
df_test.lat.fillna(method='pad', inplace=True)
df_test.lon.fillna(method='pad', inplace=True)
df_test.state.fillna(method='pad', inplace=True)
In [27]:
df_train.isnull().sum().sum()
Out[27]:
In [28]:
df_test.isnull().sum().sum()
Out[28]:
In [29]:
df_train.head()
Out[29]:
In [30]:
one_hot_encode_columns = ['agency_name', 'state', 'disposition']
In [31]:
[ df_train[c].unique().size for c in one_hot_encode_columns]
Out[31]:
In [32]:
# So remove city and states...
In [33]:
one_hot_encode_columns = ['agency_name', 'state', 'disposition']
df_train = pd.get_dummies(df_train, columns=one_hot_encode_columns)
df_test = pd.get_dummies(df_test, columns=one_hot_encode_columns)
In [34]:
df_train.head()
Out[34]:
In [35]:
from sklearn.model_selection import train_test_split
train_features = df_train.columns.drop('compliance')
train_features
Out[35]:
In [36]:
X_data, X_keep, y_data, y_keep = train_test_split(df_train[train_features],
df_train.compliance,
random_state=0,
test_size=0.05)
In [37]:
print(X_data.shape, X_keep.shape)
In [38]:
X_train, X_test, y_train, y_test = train_test_split(X_data[train_features],
y_data,
random_state=0,
test_size=0.2)
In [39]:
print(X_train.shape, X_test.shape)
In [40]:
from sklearn.neural_network import MLPClassifier
from sklearn.preprocessing import MinMaxScaler
scaler = MinMaxScaler()
X_train_scaled = scaler.fit_transform(X_train)
X_test_scaled = scaler.transform(X_test)
clf = MLPClassifier(hidden_layer_sizes = [50], alpha = 5,
random_state = 0,
solver='lbfgs')
clf.fit(X_train_scaled, y_train)
print(clf.loss_)
In [41]:
clf.score(X_train_scaled, y_train)
Out[41]:
In [42]:
clf.score(X_test_scaled, y_test)
Out[42]:
In [43]:
from sklearn.metrics import recall_score, precision_score, f1_score
train_pred = clf.predict(X_train_scaled)
print(precision_score(y_train, train_pred),
recall_score(y_train, train_pred),
f1_score(y_train, train_pred))
In [44]:
from sklearn.metrics import recall_score, precision_score, f1_score
test_pred = clf.predict(X_test_scaled)
print(precision_score(y_test, test_pred),
recall_score(y_test, test_pred),
f1_score(y_test, test_pred))
In [45]:
test_pro = clf.predict_proba(X_test_scaled)
In [46]:
def draw_roc_curve():
%matplotlib notebook
import matplotlib.pyplot as plt
from sklearn.metrics import roc_curve, auc
fpr_lr, tpr_lr, _ = roc_curve(y_test, test_pro[:,1])
roc_auc_lr = auc(fpr_lr, tpr_lr)
plt.figure()
plt.xlim([-0.01, 1.00])
plt.ylim([-0.01, 1.01])
plt.plot(fpr_lr, tpr_lr, lw=3, label='LogRegr ROC curve (area = {:0.2f})'.format(roc_auc_lr))
plt.xlabel('False Positive Rate', fontsize=16)
plt.ylabel('True Positive Rate', fontsize=16)
plt.title('ROC curve (1-of-10 digits classifier)', fontsize=16)
plt.legend(loc='lower right', fontsize=13)
plt.plot([0, 1], [0, 1], color='navy', lw=3, linestyle='--')
plt.axes().set_aspect('equal')
plt.show()
draw_roc_curve()
In [47]:
test_pro[0:10]
Out[47]:
In [48]:
clf.predict(X_test_scaled[0:10])
Out[48]:
In [49]:
y_test[0:10]
Out[49]:
In [50]:
1 - y_train.sum()/len(y_train)
Out[50]:
In [51]:
from sklearn.metrics import recall_score, precision_score, f1_score
test_pred = clf.predict(X_test_scaled)
print(precision_score(y_test, test_pred),
recall_score(y_test, test_pred),
f1_score(y_test, test_pred))
In [52]:
def draw_pr_curve():
from sklearn.metrics import precision_recall_curve
from sklearn.metrics import roc_curve, auc
precision, recall, thresholds = precision_recall_curve(y_test, test_pro[:,1])
print(len(thresholds))
idx = min(range(len(thresholds)), key=lambda i: abs(thresholds[i]-0.5))
print(idx)
print(np.argmin(np.abs(thresholds)))
closest_zero = idx # np.argmin(np.abs(thresholds))
closest_zero_p = precision[closest_zero]
closest_zero_r = recall[closest_zero]
import matplotlib.pyplot as plt
plt.figure()
plt.xlim([0.0, 1.01])
plt.ylim([0.0, 1.01])
plt.plot(precision, recall, label='Precision-Recall Curve')
plt.plot(closest_zero_p, closest_zero_r, 'o', markersize = 12, fillstyle = 'none', c='r', mew=3)
plt.xlabel('Precision', fontsize=16)
plt.ylabel('Recall', fontsize=16)
plt.axes().set_aspect('equal')
plt.show()
return thresholds
thresholds = draw_pr_curve()
In [53]:
import matplotlib.pyplot as plt
%matplotlib notebook
plt.plot(thresholds)
plt.show()
In [ ]: